/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.ajz.web;

import com.github.sd4324530.fastweixin.api.enums.OauthScope;
import com.github.sd4324530.fastweixin.company.api.config.QYAPIConfig;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.web.BaseController;
import com.jeesite.common.web.CookieUtils;
import com.jeesite.common.web.http.ServletUtils;
import com.jeesite.modules.ajz.entity.*;
import com.jeesite.modules.ajz.service.*;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.sys.wx.fw.utils.FwConfigUtil;
import com.jeesite.modules.sys.wx.fw.utils.ResultTemplateMsgUtil;
import com.jeesite.modules.sys.wx.qy.py.WeixinJSSDKSignUtil;
import com.jeesite.modules.sys.wx.qy.util.DloadImgUtil;
import com.jeesite.modules.sys.wx.qy.util.QyConfigUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

import static com.jeesite.modules.sys.utils.AjzUtils.deepCopy;
import static com.jeesite.modules.sys.utils.AjzUtils.filter;
import static com.jeesite.modules.sys.utils.Timestamp.TIMESTAMP;

/**
 * 企业信息表Controller
 *
 * @author cww
 * @version 2019-01-11
 */
@Controller
@RequestMapping(value = "${adminPath}/ajz/ajzCompanyInfo")
public class AjzCompanyInfoController extends BaseController {

    @Autowired
    private AjzCompanyInfoService ajzCompanyInfoService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private AjzRecordService ajzRecordService;
    @Autowired
    private AjzRecordProcessService ajzRecordProcessService;
    @Autowired
    private AjzModelService ajzModelService;
    @Autowired
    private AjzModelContentService ajzModelContentService;
    @Autowired
    private AjzNaturalGasService ajzNaturalGasService;
    @Autowired
    private AjzFoodSafetyService ajzFoodSafetyService;
    @Autowired
    private AjzLiquefiedGasService ajzLiquefiedGasService;
    @Autowired
    private OfficeService officeService;

    @Autowired
    private AjzCheckService ajzCheckService;
    //审核结果通知
    @Autowired
    private ResultTemplateMsgUtil resultTemplateMsgUtil;

    /**
     * 获取数据
     */
    @ModelAttribute
    public AjzCompanyInfo get(String id, boolean isNewRecord) {
        return ajzCompanyInfoService.get(id, isNewRecord);
    }


    /**
     * 企业信息页面
     * @param ajzCompanyInfo
     * @param model
     * @return
     */
    @RequiresPermissions("sys:empUser:view")
    @RequestMapping(value = "index")
    public String index(AjzCompanyInfo ajzCompanyInfo, Model model) {
        return "modules/ajz/ajzCompanyIndex";
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("ajz:ajzCompanyInfo:view")
    @RequestMapping(value = {"list", ""})
    public String list(AjzCompanyInfo ajzCompanyInfo, Model model) {
        model.addAttribute("ajzCompanyInfo", ajzCompanyInfo);
        return "modules/ajz/ajzCompanyInfoList";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("ajz:ajzCompanyInfo:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page<AjzCompanyInfo> listData(AjzCompanyInfo ajzCompanyInfo, HttpServletRequest request, HttpServletResponse response) {
        ajzCompanyInfo.setPage(new Page<>(request, response));
        Page<AjzCompanyInfo> page = ajzCompanyInfoService.findPage(ajzCompanyInfo);
        return page;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("ajz:ajzCompanyInfo:view")
    @RequestMapping(value = "form")
    public String form(AjzCompanyInfo ajzCompanyInfo, Model model) {
        model.addAttribute("ajzCompanyInfo", ajzCompanyInfo);
        return "modules/ajz/ajzCompanyInfoForm";
    }

    /**
     * 保存企业信息表
     */
    @RequiresPermissions("ajz:ajzCompanyInfo:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated AjzCompanyInfo ajzCompanyInfo) {
        ajzCompanyInfoService.save(ajzCompanyInfo);
        return renderResult(Global.TRUE, text("保存企业信息表成功！"));
    }

    /**
     * 删除企业信息表
     */
    @RequiresPermissions("ajz:ajzCompanyInfo:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(AjzCompanyInfo ajzCompanyInfo) {
        ajzCompanyInfoService.delete(ajzCompanyInfo);
        return renderResult(Global.TRUE, text("删除企业信息表成功！"));
    }


    /**
     * 导入用户数据
     */
    @ResponseBody
    @RequiresPermissions("ajz:ajzCompanyInfo:edit")
    @PostMapping(value = "importData")
    public String importData(MultipartFile file, String updateSupport) {
        try {
            boolean isUpdateSupport = Global.YES.equals(updateSupport);
            ajzCompanyInfoService.updateVariable();
            String message = ajzCompanyInfoService.importData(file, isUpdateSupport);
            return renderResult(Global.TRUE, "posfull:" + message);
        } catch (Exception ex) {
            return renderResult(Global.FALSE, "posfull:" + ex.getMessage());
        }
    }

    /**
     * 下载导入企业数据模板
     */
    @RequiresPermissions("ajz:ajzCompanyInfo:view")
    @RequestMapping(value = "importTemplate")
    public void shipinTemplate(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "公司模板.xlsx";
            String realPath = request.getSession().getServletContext().getRealPath("/downLoad/公司模板.xlsx");
            downLoadFile(realPath, response, fileName);
//			return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
//		return "redirect:" + adminPath + "/ajz/ajzBaseinfo/list?repage";
    }

    /**
     * 文件下载
     *
     * @param filePath
     * @param response
     * @param filename
     */
    @SuppressWarnings("resource")
    public void downLoadFile(String filePath, HttpServletResponse response, String filename) {
        BufferedOutputStream bufferOut = null;
        BufferedInputStream bufferIn = null;
        try {
            bufferIn = new BufferedInputStream(new FileInputStream(filePath));
            bufferOut = new BufferedOutputStream(response.getOutputStream());
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("UTF-8"), "iso8859-1"));
            byte[] Byte = new byte[1024];
            int len = 0;
            while (-1 != (len = bufferIn.read(Byte))) {
                bufferOut.write(Byte, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != bufferOut) {
                try {
                    bufferOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != bufferIn) {
                try {
                    bufferIn.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //==========================================以下是企业号的方法,序号代表流程中所在位置=========================================================

    /**
     * 跳转至专题页
     * @param model
     * @return
     */
    @RequestMapping({"typeAqsc"})
    public String typeAqsc(Model model){
        //时间戳
        model.addAttribute("Timestamp", TIMESTAMP);
        model.addAttribute("tableType","ajzCompanyInfo");
        return "modules/ajz/mobile/type_company";
    }
    /**
     * 实时获取店面专题的数据信息
     * @param status
     * @return
     */
    @RequestMapping("detailsMap")
    @ResponseBody
    public List<?> etailsMap(@Param("status") String status,@Param("dangerType") String dangerType){
        List allList = new ArrayList();
        AjzCompanyInfo title = new AjzCompanyInfo();
        AjzCompanyInfo ajzCompanyInfo = new AjzCompanyInfo();
        //设置查询条件为企业
        AjzRecord ajzRecord = new AjzRecord();
        ajzRecord.setStatus("0");//设置企业的记录为未删除的
        ajzRecord.setBaseType("company");//设置企业类型，用于查询企业类型的值
        ajzRecord.setTableType(dangerType);
        //查询有排查过的对应企业，默认为所有
        ajzCompanyInfo.setAjzRecord(ajzRecord);
        //获取默认页数
        Page page = new Page();
        page.setPageSize(10);
        page.setPageNo(1);
        ajzCompanyInfo.setPage(page);
        /*1.获取标题栏数据*/
        //全部
        int all =ajzCompanyInfoService.findAllList().size();
        //待整改
        ajzCompanyInfo.getAjzRecord().setCheckStatus("1");
        int uncheck = (int)ajzCompanyInfoService.findCount(ajzCompanyInfo);
        ajzCompanyInfo.getAjzRecord().setCheckStatus("2");
        uncheck += (int)ajzCompanyInfoService.findCount(ajzCompanyInfo);
        //已整改
        ajzCompanyInfo.getAjzRecord().setCheckStatus("3");
        ajzCompanyInfo.getAjzRecord().setTableType(dangerType);

        int checked = (int)ajzCompanyInfoService.findCount(ajzCompanyInfo);
        //待排查
        int uninspect =all-uncheck-checked;
        title.setAll(all);
        title.setUninspect(uninspect);
        title.setUncheck(uncheck);
        title.setChecked(checked);
        title.setStatus(status);//这里临时用作表示选中的标题栏

        /*2.获取对应过滤的数据列表*/
        switch (Integer.parseInt(status)){
            case 0://全部
                allList = ajzCompanyInfoService.findAllList();
                break;
            case 1://待排查  ,查询记录为空,或者状态为4
                List<String> recordBaseId = new ArrayList();
                List<String> companyBaseId = new ArrayList();

//                ajzRecord.setCheckStatus("4");
                for(AjzRecord record:ajzRecordService.findList(ajzRecord)){
                    recordBaseId.add(record.getBaseId());
                }
                for(AjzCompanyInfo companyInfo:ajzCompanyInfoService.findAllList()){
                    companyBaseId.add(companyInfo.getId());
                }

                companyBaseId.removeAll(recordBaseId);


                //同时包含检查状态为4的
                ajzRecord.setCheckStatus("4");
                recordBaseId.clear();
                for(AjzRecord record:ajzRecordService.findList(ajzRecord)){
                    recordBaseId.add(record.getBaseId());
                }
                companyBaseId.addAll(recordBaseId);
                //获取
                for(String id:companyBaseId){
                    allList.add(ajzCompanyInfoService.getById(id));
                }

                break;
            case 2://待整改
                ajzCompanyInfo.getAjzRecord().setCheckStatus("1");
                allList = ajzCompanyInfoService.findList(ajzCompanyInfo);

                //将状态为 1和2的有隐患问题,合并
                ajzCompanyInfo.getAjzRecord().setCheckStatus("2");
                allList.addAll(ajzCompanyInfoService.findList(ajzCompanyInfo));

                break;
            case 3://已整改
                ajzCompanyInfo.getAjzRecord().setCheckStatus("3");
                allList = ajzCompanyInfoService.findList(ajzCompanyInfo);

                break;
        }

        /*如果存在数据则给标题栏赋值*/
        if(title.getAll()!=0){
            allList.add(title);
        }

        return allList;
    }

    //专题页:安全生产的专题页下拉获取商家数据
    @RequestMapping({"getTypeAqscJson"})
    @ResponseBody
    public Page<AjzCompanyInfo> getTypeAqscJson(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

        //获取前端是否有类别的值，没有值为查询全部，有为查询部分
        String status = request.getParameter("status");
        String pageNo = request.getParameter("pageNo");
        //设置查询条件为企业
        AjzRecord ajzRecord = new AjzRecord();
        ajzRecord.setStatus("0");//设置企业的记录为未删除的
        ajzRecord.setBaseType("company");//设置企业类型，用于查询企业类型的值
        //如果默认查询未排查的企业，可以在else里面设置ajzRecord.setDelFlag("0")
        if(StringUtils.isNotBlank(status)){
            ajzRecord.setCheckStatus(status);//设置是否待检查，已检查等
        }
        AjzCompanyInfo ajzCompanyInfo = new AjzCompanyInfo();
        ajzCompanyInfo.setAjzRecord(ajzRecord);
        //获取页数
        Page page = new Page();
        page.setPageSize(10);
        if(StringUtils.isNotBlank(pageNo)){
            page.setPageNo(Integer.parseInt(pageNo));
        }
        ajzCompanyInfo.setPage(page);
        Page<AjzCompanyInfo> pages =ajzCompanyInfoService.findPage(ajzCompanyInfo);

        return pages;
    }



    //记录流程:跳转提交记录页面
    @RequestMapping(value = "record")
    public String record(AjzCompanyInfo ajzCompanyInfo, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {


        //获取检查人员信息
        String userCode = CookieUtils.getCookie(request, "userId");
        if(StringUtils.isBlank(userCode)){
            userCode = request.getParameter("user");
        }
        User user = UserUtils.getByLoginCode(userCode);

        //测试从其他地方进来
        if (user == null) {
            user = UserUtils.getByLoginCode("admin");
        }

        //获取上次的检查记录
        List<AjzCheck> ajzChecks= new ArrayList<>();
        List<AjzCheck> orderList=new ArrayList<>();
        List<AjzCheck> rectofication = new ArrayList<>();
        AjzRecord ajzRecord = ajzRecordService.findInfoById(ajzCompanyInfo.getId(),request.getParameter("tableType"));
        if(ajzRecord !=null){
            ajzChecks = ajzCheckService.findListByRecordProcessId(ajzRecordProcessService.findForNum(ajzRecord.getNumber()).getId());
            //将list进行深度复制
            orderList = deepCopy(ajzChecks);
            rectofication = deepCopy(ajzChecks);
            //过滤掉不要的隐患问题
            orderList = filter(orderList, "2");
            rectofication = filter(rectofication, "1");
        }

        //获取上次的检查点图片和隐患图片
        String checkUrls =  ajzRecord == null ? "" : ajzRecord.getScenePic();
        String dangerUrls =  ajzRecord == null ? "" : ajzRecord.getDangerPic();
        String[] ckls = null;
        String[] dgls = null;
        if (StringUtils.isNotBlank(checkUrls)) {
            ckls = checkUrls.split(";");
        }
        if (StringUtils.isNotBlank(dangerUrls)) {
            dgls = dangerUrls.split(";");
        }

        //获取当前用户所在机构的其他用户
        EmpUser empUser = empUserService.get(user.getUserCode());
        Employee employee = new Employee();
        if (empUser != null) {
            employee = empUser.getEmployee();
        }

        Employee otherUser = new Employee();
        otherUser.setOffice(employee.getOffice());

        EmpUser empUser1 = new EmpUser();
        empUser1.setEmployee(otherUser);

        List userList = empUserService.findList(empUser1);

        model.addAttribute("userList", userList); //返回执法人员的列表
        model.addAttribute("ckls", ckls);
        model.addAttribute("dgls", dgls);
        model.addAttribute("ajzChecks", ajzChecks); //返回复查信息
        model.addAttribute("orderList", orderList); //责令项list
        model.addAttribute("rectofication", rectofication); //待整改项list
        model.addAttribute("user", user);
        model.addAttribute("ajzCompanyInfo", ajzCompanyInfo);
        model.addAttribute("record", ajzRecord);
        model.addAttribute("tableType", request.getParameter("tableType"));

        //cookie 存值为ajz_aqsc
        CookieUtils.setCookie(response, "company", ajzCompanyInfo.getId());

        //获得微信jssdk签名等
        QYAPIConfig qyapiConfig = QyConfigUtil.getQYAPIConfig();
        String jsapi_ticket = qyapiConfig.getJsApiTicket();

        String queryString = request.getQueryString();
        String url2 = "http://" + request.getServerName() // 服务器地址
                + request.getContextPath() // 项目名称
                + request.getServletPath(); // 请求页面或其他地址
        if (queryString != null) {
            url2 += "?" + queryString;
        }
        Map<String, String> sign = WeixinJSSDKSignUtil.sign(jsapi_ticket, url2);

        //获取隐患模板的信息,包括类型和内容

        AjzModel ajzModel = new AjzModel();
        AjzModelContent ajzModelContent = new AjzModelContent();
        ajzModel.setBaseType(request.getParameter("tableType"));
        List<AjzModel> modelList = ajzModelService.findList(ajzModel);
        List<AjzModelContent> ajzModelContentList = new ArrayList<>();

        Map danModel = new LinkedHashMap<>();
        for (AjzModel am:modelList) {
            ajzModelContent.setModelId(am.getId());
            ajzModelContentList = ajzModelContentService.findList(ajzModelContent);
            danModel.put(am.getDangerType(), ajzModelContentList);
        }

        model.addAttribute("danModel", danModel);
        model.addAttribute("appId", QyConfigUtil.apiConfig.getCorpid());
        model.addAttribute("nonceStr", sign.get("nonceStr"));
        model.addAttribute("timestamp", sign.get("timestamp"));
        model.addAttribute("signature", sign.get("signature"));

        //开始检查的时间
        model.addAttribute("starTime", DateUtils.getDateTime());

        //时间戳
        model.addAttribute("Timestamp", TIMESTAMP);

        return "modules/ajz/mobile/table";
    }


    //记录流程:记录提交，展示记录页面
    @RequestMapping(value = "recordCommit")
    public String recordCommit(AjzCompanyInfo ajzCompanyInfo, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        //生成recordProcessId
        String recordProcessId = UUID.randomUUID().toString().replaceAll("-", "");

        //保存记录信息
        AjzRecord ajzRecord = ajzCompanyInfoService.saveCmtRecord(recordProcessId,ajzCompanyInfo,request);

        //保存问题项,
        List<AjzCheck> ajzChecksList = ajzCompanyInfoService.saveCmtCheck(recordProcessId,request);

        //保存生成文书,返回建议用于推送
        ajzCompanyInfoService.saveCmtFile(ajzRecord,ajzChecksList,ajzCompanyInfo,request);



        //========================================================服务号消息推送=======================================================================================
        try{
            String opinion = "";
            if(StringUtils.isNotBlank(opinion) && ajzCompanyInfo!=null && StringUtils.isNotBlank(ajzCompanyInfo.getOpenid())){
                //1.获取问题项目
                opinion = opinion.substring(0, 11)+"......";
                //2.封装消息内容
                Map<String, Object> map = new HashMap<>();
                map.put("first","您有一条新的检查消息通知：\r\n");
                map.put("keyword1","安全生产");
                map.put("keyword2",request.getParameter("starTime"));
                map.put("keyword3",opinion+"\r\n");
                map.put("remark","详情查看具体内容");
                //3.发送消息
                resultTemplateMsgUtil.sendWord(ajzCompanyInfo.getOpenid(),map);
            }
        }catch (Exception e){
            System.out.println("erro:"+e);
        }finally {
            ServletUtils.redirectUrl(request, response, adminPath + "/ajz/ajzBaseinfo/searchName?id=" + ajzCompanyInfo.getId());
            return "null";
        }

    }


    //添加企业:updateBy会是system，因为获取不到用户---UserUtils.getLoginInfo()为null
    //todo 需要做一个判断，及createBy有值时实体类.preInsert();不执行，但日期时间照常修改
    @RequestMapping(value = "addQYInfo")
    public String addQYInfo(AjzCompanyInfo ajzCompanyInfo,AjzNaturalGas ajzNaturalGas,AjzLiquefiedGas ajzLiquefiedGas,AjzFoodSafety ajzFoodSafety, HttpServletRequest request, HttpServletResponse response, Model model) {
        //获取用户数据
        String userId = QyConfigUtil.getUserId(request,response);
        //传入用户数据
        ajzCompanyInfo.setUpdateBy(userId);
        ajzCompanyInfo.setCreateBy(userId);
        ajzNaturalGas.setCreateBy(userId);
        ajzNaturalGas.setUpdateBy(userId);
        ajzLiquefiedGas.setCreateBy(userId);
        ajzLiquefiedGas.setUpdateBy(userId);
        ajzFoodSafety.setCreateBy(userId);
        ajzFoodSafety.setUpdateBy(userId);


        //记录的创建者默认为system，所以ajzRecord可以不用设置system。ajzRecord此处必须设置为system的原因是未排查的数据不需要被统计（及按照人名统计时，可以不计入统计内）
        AjzRecord ajzRecord = new AjzRecord();
        ajzRecord.setCheckStatus("0");
        ajzRecord.setBaseType("company");
        ajzRecord.setTableType("ajz_aqsc");//（临时）
        ajzCompanyInfo.setAjzRecord(ajzRecord);
        String signboard = request.getParameter("imgBox1");
        String enterprisePicture = request.getParameter("imgBox");

        String officeName = EmpUtils.getOffice(ajzCompanyInfo.getOffice().getOfficeCode()).getOfficeName();

        //创建保存在文件管理器中的文件路径
        String filePath =  Global.getUserfilesBaseDir(officeName + File.separator +"企业" + File.separator +ajzCompanyInfo.getEnterpriseName()+ File.separator );
        //创建保存数据库的图片路径
        String savePath = request.getContextPath() + File.separator +"userfiles"+ File.separator + officeName + File.separator +  "企业" + File.separator +ajzCompanyInfo.getEnterpriseName() + File.separator ;
        FileUtils.createDirectory(filePath);


//        保存户外照片
        if (!StringUtils.isBlank(signboard)) {
            signboard = DloadImgUtil.downloadMedia(QyConfigUtil.getAccessToken(),"outdoor",signboard, savePath, filePath);
        }
//        保存营业照片
        if (!StringUtils.isBlank(enterprisePicture)) {
            enterprisePicture = DloadImgUtil.downloadMedia(QyConfigUtil.getAccessToken(), "cert",enterprisePicture, savePath, filePath);
        }
        ajzCompanyInfo.setSignboard(signboard);
        ajzCompanyInfo.setEnterprisePicture(enterprisePicture);

        ajzCompanyInfo.setCycleIndex("1");
        ajzCompanyInfo.setCheckStatus("0"); //默认为未检查

        //需要给创建的东西添加用户
        ajzCompanyInfoService.save(ajzCompanyInfo);
//        保存记录需要添加企业的id，所以需要放在企业保存之后
        //获取企业id
        String ajzCompanyInfoId = ajzCompanyInfo.getId();
        //保存信息
//        ajzRecord.setBaseId(ajzCompanyInfoId);
//        ajzRecordService.save(ajzRecord);
//        //recordProcess也需添加一条
//        ajzRecordProcessService.saveRecord(ajzRecord);
        //保存天然气的信息
        ajzNaturalGas.setBaseId(ajzCompanyInfoId);
        ajzNaturalGasService.save(ajzNaturalGas);
        //保存液化气的信息
        ajzLiquefiedGas.setBaseId(ajzCompanyInfoId);
        ajzLiquefiedGasService.save(ajzLiquefiedGas);
        //保存食品安全的信息
        ajzFoodSafety.setBaseId(ajzCompanyInfoId);
        ajzFoodSafetyService.save(ajzFoodSafety);

        ServletUtils.redirectUrl(request, response, adminPath + "/ajz/ajzBaseinfo/searchName?id=" + ajzCompanyInfo.getId());

        return null;
    }


    //修改:跳转到企业修改页面
    @RequestMapping(value = "updateInfo")
    public String updateInfo(HttpServletRequest request, HttpServletResponse response, Model model) {
        //查询企业的基本信息
        String id = request.getParameter("id");
        AjzCompanyInfo ajzCompanyInfo = ajzCompanyInfoService.get(id);
        model.addAttribute("ajzCompanyInfo",ajzCompanyInfo);
        //或者默认一个父级机构的名称
        Office office = new Office();
        office.setParentCode(ajzCompanyInfo.getOffice().getParentCode());
        List<Office> officeList = officeService.findList(office);
        model.addAttribute("officeList",officeList);
        //获得微信jssdk签名等
        QyConfigUtil.getJSSDKSign(request,model);
        //时间戳
        model.addAttribute("Timestamp", TIMESTAMP);
        return "modules/ajz/mobile/update_baseinfo";
    }

    //修改:执行企业修改
    @RequestMapping(value = "updateQYInfo")
    public String updateQYInfo(AjzCompanyInfo ajzCompanyInfo,HttpServletRequest request, HttpServletResponse response, Model model) {
        //获取用户数据
        String userId = QyConfigUtil.getUserId(request,response);
        if(userId==null){
            userId = "system";
        }
        //传入用户数据
        ajzCompanyInfo.setUpdateBy(userId);
        ajzCompanyInfo.getAjzNaturalGas().setUpdateBy(userId);
        ajzCompanyInfo.getAjzLiquefiedGas().setUpdateBy(userId);
        ajzCompanyInfo.getAjzFoodSafety().setUpdateBy(userId);

        String signboard = request.getParameter("imgBox1");
        String enterprisePicture = request.getParameter("imgBox");

        //创建保存在文件管理器中的文件路径
        String filePath =  Global.getUserfilesBaseDir(ajzCompanyInfo.getOffice().getOfficeName() + File.separator + "企业" + File.separator +ajzCompanyInfo.getEnterpriseName() + File.separator );
        //创建保存数据库的图片路径
        String savePath = request.getContextPath() + File.separator +"userfiles"+ File.separator + ajzCompanyInfo.getOffice().getOfficeName() + File.separator + "企业" + File.separator +ajzCompanyInfo.getEnterpriseName() + File.separator;
        FileUtils.createDirectory(filePath);

//        保存户外照片,如果不为空的时候，则修改图片
        if (StringUtils.isNotBlank(signboard)) {
            signboard = DloadImgUtil.downloadMedia(QyConfigUtil.getAccessToken(),"outdoor",signboard, savePath, filePath);
            ajzCompanyInfo.setSignboard(signboard);
        }
//        保存营业照片,如果不为空的时候，则修改图片
        if (StringUtils.isNotBlank(enterprisePicture)) {
            enterprisePicture = DloadImgUtil.downloadMedia(QyConfigUtil.getAccessToken(), "cert",enterprisePicture, savePath, filePath);
            ajzCompanyInfo.setEnterprisePicture(enterprisePicture);
        }


        //需要给创建的东西添加用户
        ajzCompanyInfoService.update(ajzCompanyInfo);
        // 更新企业涉及的类型信息
        ajzCompanyInfoService.updateTypesInvolved(
                ajzCompanyInfo.getAjzNaturalGas(),
                ajzCompanyInfo.getAjzLiquefiedGas(),
                ajzCompanyInfo.getAjzFoodSafety(),
                ajzCompanyInfo.getId());

        ServletUtils.redirectUrl(request, response, adminPath + "/ajz/ajzBaseinfo/searchName?id=" + ajzCompanyInfo.getId());

        return null;
    }


    //校验:根据营业执照号码判断是否已存在商家
    @RequestMapping(value = "checkEnterpriseNum")
    @ResponseBody
    public AjzCompanyInfo checkEnterpriseNum(AjzCompanyInfo ajzCompanyInfo,HttpServletRequest request, HttpServletResponse response) {
        AjzCompanyInfo ajzCompanyInfo1 = ajzCompanyInfoService.findajzCompanyInfoByEnterpriseId(ajzCompanyInfo.getEnterpriseNum());
        return ajzCompanyInfo1;
    }



    /**
     * 移动端添加企业信息
     */
    //==========================================以下为服务号的方法,序号代表流程中所在位置=========================================================
    //1.服务号绑定企业
    @RequestMapping({"wechatIndex"})
    public String wechatIndex(Model model, HttpServletRequest request, HttpServletResponse response) {
        //获得微信jssdk签名等
        QyConfigUtil.getJSSDKSign(request,model);
        //获取openid
        String openid = FwConfigUtil.getOpenId(request, response);
        if (StringUtils.isEmpty(openid)) {
            String oauthPageUrl = FwConfigUtil.getOauthAPI().getOauthPageUrl(request.getRequestURL().toString(), OauthScope.SNSAPI_BASE, "1");
            ServletUtils.redirectUrl(request, response, oauthPageUrl);
        }
        AjzCompanyInfo ajzCompanyInfo = ajzCompanyInfoService.findAjzCompanyInfoByOpenid(openid);
        //openid没有绑定，则跳转绑定页面
        if (ajzCompanyInfo == null) {
            model.addAttribute("openid", openid);
            return "modules/ajz/mobile/wechat/addqiye";
        } else {
            //跳转商家自检
            /*        String checkId = (ajzRecordService.findByAjzCompanyInfo(ajzCompanyInfo.getId()).getId());*/
            String checkId = null;

            if (checkId == null || checkId == "") {
                model.addAttribute("ajzCompanyInfo", ajzCompanyInfo);
                model.addAttribute("openid", openid);
                model.addAttribute("checkId", checkId);
                return "modules/ajz/mobile/wechat/index";
            } else {
                AjzRecord record = ajzRecordService.findInfoById(ajzCompanyInfo.getId(),request.getParameter("tableType"));
                List<AjzRecordProcess> list = ajzRecordProcessService.findListByInfoId(record);
                model.addAttribute("list", list);
                if (list.size() == 0) {
                    List<AjzRecord> list1 = ajzRecordService.findListByInfoId(record);
                    model.addAttribute("list", list1);
                }
                model.addAttribute("userId", record.getUpdateBy());
                model.addAttribute("ajzCompanyInfo", ajzCompanyInfo);
                model.addAttribute("status", ajzCompanyInfo.getStatus());
                model.addAttribute("checkId", checkId);
                model.addAttribute("openid", openid);
                return "modules/ajz/mobile/wechat/index";
            }
        }
    }

    //服务号-->跳转用户绑定页面
   /* @RequestMapping({"selfCheckRecord"})
    public String selfCheckRecord(Model model,HttpServletRequest request) {

        String openid = request.getParameter("openid");
        String ajzcompanyInfoId = request.getParameter("companyInfoId");
         AjzCompanyInfo ajzCompanyInfo = ajzCompanyInfoService.findAjzCompanyInfoByOpenid(openid);
        if(ajzCompanyInfo == null){
            ajzCompanyInfo = ajzCompanyInfoService.get(ajzcompanyInfoId);
        }
        String checkId = ajzCompanyInfo.getCheckId();
        AjzRecord record = ajzRecordService.findByCheckId(ajzCompanyInfo.getCheckId());
        List<AjzRecordProcess> list = ajzRecordProcessService.findListByInfoId(record);
        model.addAttribute("list", list);
        if (list.size() == 0) {
            List<AjzRecord> list1 = ajzRecordService.findListByInfoId(record);
            model.addAttribute("list", list1);
        }
        model.addAttribute("userId", record.getUpdateBy());
        model.addAttribute("ajzCompanyInfo", ajzCompanyInfo);
        model.addAttribute("checkId", checkId);
        model.addAttribute("openid", openid);
        return "modules/wechat/self_inspection";
    }*/

    //用于注册成功后中转
    @RequestMapping({"change"})
    public String registerChange(AjzRecord record, Model model, HttpServletRequest request) {
        String companyInfoId = request.getParameter("companyInfoId");
        String openid = request.getParameter("openid");
        //商家自检或检查记录
//        String type = request.getParameter("type");
        AjzCompanyInfo ajzCompanyInfo = ajzCompanyInfoService.get(companyInfoId);
//        String checkId = ajzBaseinfo.getCheckId();

        AjzRecord ajzRecord = ajzRecordService.findInfoById(ajzCompanyInfo.getId(),request.getParameter("tableType"));
        if (ajzRecord == null) {

        } else {
            model.addAttribute("userId", ajzRecord.getUpdateBy());
        }

        /*model.addAttribute("checkId", checkId);*/
        model.addAttribute("ajzCompanyInfo", ajzCompanyInfo);
        model.addAttribute("status", ajzCompanyInfo.getStatus());
        model.addAttribute("openid", openid);

        return "modules/ajz/mobile/wechat/index";
    }

    @RequestMapping(value = "fwaddQYInfo")
    public String fwaddQYInfo(AjzCompanyInfo ajzCompanyInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
        String openid = request.getParameter("openid");
        String enterpriseId = request.getParameter("enterpriseId");
        String only = request.getParameter("only");

        AjzCompanyInfo info ;
        //根据营业执照号码绑定企业
        if (only.equals("1")) {//根据营业执照号码查询到该企业
            info = ajzCompanyInfoService.findajzCompanyInfoByEnterpriseId(enterpriseId);
            if (info != null) {
                ajzCompanyInfo =ajzCompanyInfoService.get(info.getId());
                ajzCompanyInfo.setOpenid(openid);
                ajzCompanyInfoService.save(ajzCompanyInfo);
                System.out.println(ajzCompanyInfo.getId());
//            return "modules/wechat/index?baseinfoId=" + ajzBaseinfo.getId();
                return "redirect:" + Global.getAdminPath() + "/ajz/ajzCompanyInfo/change?companyInfoId=" + ajzCompanyInfo.getId()+"&oprnid="+openid;
            } else {

                return "modules/ajz/mobile/wechat/addqiye";
            }
        } else {

            ajzCompanyInfoService.save(ajzCompanyInfo);
            return "redirect:" + Global.getAdminPath() + "/ajz/ajzCompanyInfo/change?companyInfoId=" + ajzCompanyInfo.getId()+"&oprnid="+openid;
        }
    }
    @RequestMapping(value = "nameCheck")
    @ResponseBody
    public Map enterpriseNameCheck(HttpServletRequest request) {
        String flag = "";
        String enterpriseId = request.getParameter("msg");
        AjzCompanyInfo companyInfo = ajzCompanyInfoService.findajzCompanyInfoByEnterpriseId(enterpriseId);
        if(companyInfo==null){
            flag = "fail";
        }else{
            flag = "success";
        }
        Map map = new HashMap();
        map.put("flag",flag);
        return map;
    }



    //==========================================以下是地点上图功能=========================================================

    /**
     * 企业上图
     */
    @RequiresPermissions("sys:empUser:view")
    @RequestMapping(value = "enterpriseMap")
    public String enterpriseMap() {
        return "modules/ajz/enterpriseMap";
    }

    /**
     * 小地图获取项目名称
     */
    @RequestMapping("getCompanyInfo")
    @ResponseBody//此注解不能省略 否则ajax无法接受返回值
    public String getCompanyInfo(AjzCompanyInfo ajzCompanyInfo, HttpServletRequest request) {
        String id = request.getParameter("id");
        ajzCompanyInfo.setId(id);
        ajzCompanyInfo = ajzCompanyInfoService.get(ajzCompanyInfo);
        String enterpriseName = ajzCompanyInfo.getEnterpriseName();
        return enterpriseName;
    }

    /**
     * 小地图
     */
    @RequiresPermissions("sys:empUser:view")
    @RequestMapping(value = "smallMap")
    public String smallMap(AjzCompanyInfo ajzCompanyInfo, Model model) {
        model.addAttribute("ajzCompanyInfo", ajzCompanyInfo);
        return "modules/ajz/smallMap";
    }


    //后台企业导出
    @RequiresPermissions("sys:empUser:view")
    @RequestMapping(value = "exportCompany")
    public void exportCompany(HttpServletResponse response,AjzCompanyInfo ajzCompanyInfo) {

        List<AjzCompanyInfo> companyList = ajzCompanyInfoService.findList(ajzCompanyInfo);
        String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
        try (ExcelExport ee = new ExcelExport("用户数据", AjzCompanyInfo.class)) {
            ee.setDataList(companyList).write(response, fileName);
        }
    }

}